# coding: utf-8
import os, sys
import time
import datetime, pprint
from PyQt4 import QtCore

class TaskThread (QtCore.QThread):
    def __init__(self, store):
        super(TaskThread, self).__init__()
        self.store = store
        self.task_timeout = QtCore.SIGNAL("taskTimeout(PyQt_PyObject)")        

    def run(self):
        while True:
            self.check()
            time.sleep(10)

    def check(self):
        dt = datetime.datetime.now()
        data = self.store.copy()
        
        #print '-' * 60
        #pprint.pprint(data)
        for row in data:
            dte  = row['date']
            tm   = row['time']
            loop = row['loop']
            last = row['lasttime']

            if last > 0 and not loop:
                continue
            
            if loop:
                dt2 = datetime.datetime(dt.year, dt.month, dte[2], tm[0], tm[1])
            else:
                dt2 = datetime.datetime(dte[0], dte[1], dte[2], tm[0], tm[1])
            
            tm2 = int(time.mktime(dt2.timetuple()))
            if row['lasttime'] > tm2:
                continue
                
            if dt >= dt2:
                self.emit(self.task_timeout, row)
                self.store.lasttime_refresh(row['id'])
                #row['lasttime'] = int(time.time())
                #self.store.dump()
                   

